package com.itlhc.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest rq = (HttpServletRequest)request;
        HttpServletResponse rp = (HttpServletResponse)response;
        Object admin = rq.getSession().getAttribute("userSession");
        //indexOf()方法是区分大小写的!如果要检索的字符串值没有出现，则该方法返回-1。
        if(admin == null && rq.getRequestURI().indexOf("/login") == -1){
            // 没有登录 强制跳转到登录页面
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }else{
            // 已经登录，继续请求下一级资源（继续访问）
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}

